package id.net.iconpln.bb.client.view;

import id.net.iconpln.bb.client.service.MasterRPCService;
import id.net.iconpln.bb.client.service.MasterRPCServiceAsync;
import id.net.iconpln.bb.client.service.TransportRPCService;
import id.net.iconpln.bb.client.service.TransportRPCServiceAsync;
import id.net.iconpln.bb.client.tools.ComboPembangkitPemasok;
import id.net.iconpln.bb.client.util.ClientModule;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.core.FastMap;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.StoreEvent;
import com.extjs.gxt.ui.client.store.StoreListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.DateTimePropertyEditor;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.MultiField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.TimeField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class PageBbTransportPengajuanJadwal extends LayoutContainer {
	private final TransportRPCServiceAsync service = GWT.create(TransportRPCService.class);
	private final MasterRPCServiceAsync serviceMaster = GWT.create(MasterRPCService.class);
	private DateField txtTgl, txtTglEta, txtTglEtd;
	private TimeField txtEta, txtEtd;
	private ListStore storePengajuan, storeResult, storeKontrak, storeTransportir;
	private Grid gridBefore;
	private TextField txtTs, txtHgi, txtTm, txtNoJadwal, txtNoPengajuan, txtVolume, txtJumlah, txtAsh, txtCv;
	private ComboBox cboPembangkitEntry, cboKontrakEntry, cboTransportir;
	private FormPanel panel;
	
	
	  @Override  
	  protected void onRender(Element parent, int index) {  
	    super.onRender(parent, index);  
	    setLayout(new FitLayout());	    
	    initStore();
	    
	    ContentPanel cp = new ContentPanel();  	   
	    cp.setHeaderVisible(false);
	    cp.setFrame(true);  
	    cp.setLayout(new RowLayout(Orientation.HORIZONTAL));	  
	    
	    panel = createForm(); 
	    panel.setScrollMode(Scroll.AUTO);
	    
	    ContentPanel p = new ContentPanel();
	    p.setHeaderVisible(false);
	    p.setLayout(new RowLayout(Orientation.VERTICAL));	    
	    
	    ContentPanel cpShip = new ContentPanel();
	    cpShip.setLayout(new FitLayout());
	    gridBefore = createGridBefore();
	    gridBefore.addListener(Events.CellClick, new Listener<BaseEvent>() {            
            public void handleEvent(BaseEvent ge) {
            	txtNoJadwal.setValue(gridBefore.getSelectionModel().getSelectedItem().get("no_jadwal"));
            	cboPembangkitEntry.setRawValue(gridBefore.getSelectionModel().getSelectedItem().get("nama_pembangkit").toString());
            	cboTransportir.setRawValue(gridBefore.getSelectionModel().getSelectedItem().get("nama_transportir").toString());
            	cboKontrakEntry.setRawValue(gridBefore.getSelectionModel().getSelectedItem().get("no_pln_pjbb").toString());
            	txtTgl.setRawValue(gridBefore.getSelectionModel().getSelectedItem().get("tanggal").toString());
            	txtTglEtd.setRawValue(gridBefore.getSelectionModel().getSelectedItem().get("tanggal_td").toString());
            	txtEtd.setRawValue(gridBefore.getSelectionModel().getSelectedItem().get("jam_td").toString());
            	txtTglEta.setRawValue(gridBefore.getSelectionModel().getSelectedItem().get("tanggal_ta").toString());
            	txtEta.setRawValue(gridBefore.getSelectionModel().getSelectedItem().get("jam_ta").toString());
            	txtVolume.setRawValue(gridBefore.getSelectionModel().getSelectedItem().get("volume").toString());
            }
		});
	    cpShip.add(gridBefore);
	    
	    ToolBar tbJadwal = new ToolBar();
	    tbJadwal.add(new LabelToolItem("<b>Data Pengajuan Jadwal</b>"));
	    tbJadwal.add(new SeparatorToolItem());
	    p.setTopComponent(tbJadwal);
	    
	    p.add(cpShip, new RowData(1, 1));
	    
	    cp.add(panel, new RowData(.40, .80));
	    cp.add(p, new RowData(.60, .99));	    
	    add(cp, new FitData(5));  
	    
	  }  
	  
	  private void getListPengajuan(String no_pln_pjbb, String status, String id_pltu){
		  Map mapParam = new FastMap();
  		  mapParam.put("no_pln_pjbb", no_pln_pjbb);
  		  mapParam.put("id_pltu", id_pltu);
  		  mapParam.put("id_pemasok", "");
  		  mapParam.put("status", status);
  		  
  		  service.getListPengendalian("PENGAJUAN_JADWAL", mapParam,new AsyncCallback<List<Map>>() {
  			public void onFailure(Throwable caught) {
  				GWT.log(caught.getMessage(), null);
  			}

  			public void onSuccess(List<Map> result) {	
  				storePengajuan.removeAll();
  				storePengajuan.add(ClientModule.setListBaseModelFromListMap(result));
  			}
  		  });
	  }
	  
	  private void initStore(){
		  storePengajuan = new ListStore(); 
		  storeKontrak = new ListStore();	  
		  storeResult = new ListStore(); 
		  storeTransportir = new ListStore(); 
		  
		  storeResult.addStoreListener(new StoreListener<ModelData>(){
			  @Override
				public void storeAdd(StoreEvent<ModelData> se) {
					super.storeAdd(se);
					MessageBox.alert("Information", se.getModels().get(0).get("message").toString(), null);  
				}			  
		  });
	  }
	  
	  private Grid createGridBefore(){		    		  
		  List<ColumnConfig> configs = new ArrayList<ColumnConfig>();  

		    ColumnConfig column = new ColumnConfig();	 
		    column = new ColumnConfig("no_jadwal", "No Jadwal", 150);  
		    configs.add(column);  
		    
		    column = new ColumnConfig("no_pln_pjbb", "No Kontrak PJBB", 150);  
		    configs.add(column); 

		    column = new ColumnConfig("nama_pembangkit", "PLTU", 100);  
		    configs.add(column);  	
		    
		    column = new ColumnConfig("nama_transportir", "Transportir", 100);  
		    configs.add(column);  
		    		  
		    column = new ColumnConfig("tanggal", "Tanggal", 100);  
		    configs.add(column);
		    
		    column = new ColumnConfig("tgl_ta", "Tgl TA", 150);  
		    configs.add(column);
		    
		    column = new ColumnConfig("tgl_td", "Tgl TD", 150);  
		    configs.add(column);
		    
		    column = new ColumnConfig("volume", "Vol (Ton)", 150);  
		    configs.add(column);
		    
		    column = new ColumnConfig("status", "Status", 150);  
		    configs.add(column);
		    storePengajuan.setMonitorChanges(true);  
		    ColumnModel cm = new ColumnModel(configs);
		    gridBefore = new Grid(storePengajuan, cm);  
		    gridBefore.getView().setEmptyText("Data Empty");  
		    gridBefore.setBorders(false);  	
		    return gridBefore;  
	  }   
	  
	  private FormPanel createForm() {  		
	    final FormPanel panel = new FormPanel();	    
	    panel.setHeaderVisible(false);
	    
	    FieldSet fieldSet = new FieldSet();  
	    fieldSet.setHeading("Entry Pengajuan Jadwal");  
	    fieldSet.setCollapsible(false);
	  
	    FormLayout layout = new FormLayout();  
	    layout.setLabelWidth(100);  
	    fieldSet.setLayout(layout);  
	    
	    txtNoJadwal = new TextField();
	    txtNoJadwal.setName("no_jadwal");  
	    txtNoJadwal.setFieldLabel("No Jadwal");	    
	    txtNoJadwal.setReadOnly(true);
	    fieldSet.add(txtNoJadwal);
	    
	    cboPembangkitEntry = new ComboPembangkitPemasok(Registry.get("idPltu").toString());
	    cboPembangkitEntry.addSelectionChangedListener(new SelectionChangedListener<ModelData>() {
	    	@Override
	    	public void selectionChanged(SelectionChangedEvent<ModelData> se) {
	    		// TODO Auto-generated method stub
	    		Map map = new FastMap();
	    		map.put("id_pltu", se.getSelectedItem().get("id_pltu"));
	    		map.put("id_pemasok", Registry.get("idPltu").toString());
	    		serviceMaster.getMaster("KONTRAK_PLTU", map,new AsyncCallback<List<Map>>() {
	    			public void onFailure(Throwable caught) {
	    				GWT.log(caught.getMessage(), null);
	    			}

	    			public void onSuccess(List<Map> result) {	
	    				storeKontrak.removeAll();
	    				storeKontrak.add(ClientModule.setListBaseModelFromListMap(result));
	    			}
	    		});
	    	}
		});
	    fieldSet.add(cboPembangkitEntry);
	    
	    cboKontrakEntry = new ComboBox();  
	    cboKontrakEntry.setName("no_pln_pjbb");  
	    cboKontrakEntry.setFieldLabel("No PLN PJBB");
	    cboKontrakEntry.setEmptyText("Select NO PJBB...");  
	    cboKontrakEntry.setDisplayField("no_pln_pjbb");  
	    cboKontrakEntry.setWidth(200);  
	    cboKontrakEntry.setStore(storeKontrak);  
	    cboKontrakEntry.setTypeAhead(true);  
	    cboKontrakEntry.setTriggerAction(TriggerAction.ALL); 
	    cboKontrakEntry.addSelectionChangedListener(new SelectionChangedListener<ModelData>() {
	    	@Override
	    	public void selectionChanged(SelectionChangedEvent<ModelData> se) {
	    		// TODO Auto-generated method stub
	    		Map map = new FastMap();
	    		map.put("id_pemasok", se.getSelectedItem().get("id_pemasok"));
	    		serviceMaster.getMaster("TRANSPORTIR_BY_PEMASOK", map,new AsyncCallback<List<Map>>() {
	    			public void onFailure(Throwable caught) {
	    				GWT.log(caught.getMessage(), null);
	    			}

	    			public void onSuccess(List<Map> result) {
	    				storeTransportir.removeAll();
	    				storeTransportir.add(ClientModule.setListBaseModelFromListMap(result));
	    			
	    				getListPengajuan(cboKontrakEntry.getRawValue(), "NEW", cboPembangkitEntry.getValue().get("id_pltu").toString());
	    			}
	    		});
	    	}
		});
	    fieldSet.add(cboKontrakEntry);
	    
	    cboTransportir = new ComboBox();  
	    cboTransportir.setName("nama_transportir");  
	    cboTransportir.setFieldLabel("Transportir");
	    cboTransportir.setEmptyText("Select Transportir...");  
	    cboTransportir.setDisplayField("nama_transportir");  
	    cboTransportir.setWidth(200);  
	    cboTransportir.setStore(storeTransportir);  
	    cboTransportir.setTypeAhead(true);  
	    cboTransportir.setTriggerAction(TriggerAction.ALL); 
	    fieldSet.add(cboTransportir);
	    
	    txtTgl = new DateField(); 
	    txtTgl.setName("tanggal");
	    txtTgl.setPropertyEditor(new DateTimePropertyEditor("dd/MM/yyyy"));
	    txtTgl.setFieldLabel("Tanggal");  
	    txtTgl.setData("text", "Enter Tanggal");   
	    txtTgl.setValue(new Date());
	    fieldSet.add(txtTgl);	
	    
	    txtTglEtd = new DateField(); 
	    txtTglEtd.setName("tanggal_etd");
	    txtTglEtd.setPropertyEditor(new DateTimePropertyEditor("dd/MM/yyyy"));
	    txtTglEtd.setFieldLabel("Tanggal ETD");  
	    txtTglEtd.setData("text", "Enter Tanggal ETD");  
	    txtTglEtd.setWidth(100);
	    
	    txtEtd = new TimeField();
	    txtEtd.setName("time_etd");
	    txtEtd.setData("text", "Enter ETD"); 
	    txtEtd.setWidth(100);
	    txtEtd.setFormat(DateTimeFormat.getFormat("HH:mm"));
	    txtEtd.setIncrement(15);
	    
	    MultiField mfPanel1 = new MultiField();
	    mfPanel1.setSpacing(10);
	    mfPanel1.setFieldLabel("ETD");
	    mfPanel1.add(txtTglEtd);
	    mfPanel1.add(txtEtd);	    
	    fieldSet.add(mfPanel1);	   
	    
	    txtTglEta = new DateField(); 
	    txtTglEta.setName("tanggal_eta");
	    txtTglEta.setPropertyEditor(new DateTimePropertyEditor("dd/MM/yyyy"));
	    txtTglEta.setFieldLabel("Tanggal ETA");  
	    txtTglEta.setData("text", "Enter Tanggal ETA");    
	    txtTglEta.setWidth(100);
	    
	    txtEta = new TimeField();
	    txtEta.setName("time_eta");
	    txtEta.setFieldLabel("ETA");  
	    txtEta.setFormat(DateTimeFormat.getFormat("HH:mm"));
	    txtEta.setIncrement(15);
	    txtEta.setWidth(100);
	    
	    MultiField mfPanel2 = new MultiField();
	    mfPanel2.setSpacing(10);
	    mfPanel2.setFieldLabel("ETA");
	    mfPanel2.add(txtTglEta);
	    mfPanel2.add(txtEta);
	    fieldSet.add(mfPanel2);	
	    
	    txtVolume = new TextField();
	    txtVolume.setName("volume");  
	    txtVolume.setFieldLabel("Volume");	    
	    fieldSet.add(txtVolume);
	    
	    panel.add(fieldSet);  	

	    ContentPanel p = new ContentPanel();
	    p.setHeaderVisible(false);	    
	    p.setButtonAlign(HorizontalAlignment.RIGHT);  
	    	    
	    p.addButton(new Button("Submit", new SelectionListener<ButtonEvent>() {  
	      @Override  
	      public void componentSelected(ButtonEvent ce) { 
	    	  	Map mapParam = new FastMap();	    	  	
	    		mapParam.put("id_pemasok", cboKontrakEntry.getValue().get("id_pemasok"));	    		
	    		mapParam.put("id_transportir", cboTransportir.getValue().get("id_transportir"));
	    		mapParam.put("id_pltu", cboPembangkitEntry.getValue().get("id_pltu"));
	    		mapParam.put("tanggal", txtTgl.getRawValue());
	    		mapParam.put("volume", txtVolume.getRawValue());
	    		mapParam.put("tgl_ta", txtTglEta.getRawValue() + " " + txtEta.getRawValue());	    		
	    	    mapParam.put("tgl_td", txtTglEtd.getRawValue() + " " + txtEtd.getRawValue());
	    		mapParam.put("user", Registry.get("whoAmI").toString());
	    		mapParam.put("app_access", "WEB");	    
	    		mapParam.put("no_pln_pjbb", cboKontrakEntry.getValue().get("no_pln_pjbb"));
	    		mapParam.put("no_jadwal", txtNoJadwal.getRawValue());
	    		if (txtNoJadwal.getRawValue().equals("")){
	    			mapParam.put("crud", "CREATE");
	    		}else{
	    			mapParam.put("crud", "UPDATE");	    			
	    		}
	    		service.insertPengendalianBB("PENGAJUAN_JADWAL", mapParam,new AsyncCallback<List<Map>>() {
	    			public void onFailure(Throwable caught) {
	    				GWT.log(caught.getMessage(), null);
	    			}
	
	    			public void onSuccess(List<Map> result) {
	    				storeResult.removeAll();
	    				storeResult.add(ClientModule.setListBaseModelFromListMap(result));
	    				    				
	    				getListPengajuan(cboKontrakEntry.getValue().get("no_pln_pjbb").toString(), "", 
	  		    			  cboPembangkitEntry.getValue().get("id_pltu").toString());
	    			}
	    		});
	      }  
	    }));  
	    
	    p.addButton(new Button("Delete", new SelectionListener<ButtonEvent>() {  
		      @Override  
		      public void componentSelected(ButtonEvent ce) {  
		    	  Map mapParam = new FastMap();	    	  	
		    		mapParam.put("id_pemasok", "0");	    		
		    		mapParam.put("id_transportir", "0");
		    		mapParam.put("id_pltu", "0");
		    		mapParam.put("tanggal", txtTgl.getRawValue());
		    		mapParam.put("volume", txtVolume.getRawValue());
		    		mapParam.put("tgl_ta", txtTglEta.getRawValue() + " " + txtEta.getRawValue());	    		
		    	    mapParam.put("tgl_td", txtTglEtd.getRawValue() + " " + txtEtd.getRawValue());
		    		mapParam.put("user", Registry.get("whoAmI").toString());
		    		mapParam.put("app_access", "WEB");	    	
	    			mapParam.put("crud", "DELETE");
	    			mapParam.put("no_pln_pjbb", cboKontrakEntry.getValue().get("no_pln_pjbb"));
		    		mapParam.put("no_jadwal", txtNoJadwal.getRawValue());
		    		service.insertPengendalianBB("PENGAJUAN_JADWAL", mapParam,new AsyncCallback<List<Map>>() {
		    			public void onFailure(Throwable caught) {
		    				GWT.log(caught.getMessage(), null);
		    			}
		
		    			public void onSuccess(List<Map> result) {	
		    				storeResult.removeAll();
		    				storeResult.add(ClientModule.setListBaseModelFromListMap(result));
		    				
		    				getListPengajuan(cboKontrakEntry.getValue().get("no_pln_pjbb").toString(), "", 
			  		    			  cboPembangkitEntry.getValue().get("id_pltu").toString());
		    				panel.reset();
		    			}
		    		});
		      }  
		    }));  
	    
	    p.addButton(new Button("Reset", new SelectionListener<ButtonEvent>() {  
		      @Override  
		      public void componentSelected(ButtonEvent ce) {  
		    	  panel.reset();
		      }  
		    }));  

	    panel.add(p);
	    
	    return panel;  
	  }  


}
